package des.wangku.operate.standard.webserver.control;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;

import des.wangku.operate.standard.tools.Sha1;
import des.wangku.operate.standard.utls.UtilsUrlCertificate;

/**
 * Created by Administrator on 2019/11/18 0018. 给专题项目提供的获取微信接口js签名
 */
@Controller
@RequestMapping("")
public class WxShareController {
	/** 日志 */
	static Logger logger = LoggerFactory.getLogger(WxShareController.class);

	@RequestMapping(value = "/zt/wxShare/getSign", method = {
			RequestMethod.GET, RequestMethod.POST
	})
	@ResponseBody
	public JSONObject getSign(HttpServletRequest request, String url) {
		String appid = "";// "wx868bbb233d5c7b1e";//公众号ID
		String secret = "";// "5efeffc3f675bbc1e3339d6ffd3ac13e";//秘钥
		JSONObject result = new JSONObject();
		try {
			String jsapiTicket = this.getJsapiTicket(appid, secret);
			if (!StringUtils.isEmpty(jsapiTicket)) {
				String noncestr = this.getRandomString();
				long timestamp = System.currentTimeMillis() / 1000;
				String sourceString = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
				String signature = new Sha1().getDigestOfString(sourceString.getBytes());
				result.put("appid", appid);
				result.put("time", timestamp);
				result.put("nonce", noncestr);
				result.put("sign", signature);
			}
			logger.debug("获取微信分享签名，url=" + url + ", result=" + result);
		} catch (Exception e) {
			logger.debug("getSign出错", e);
		}
		return result;
	}

	/***
	 * 获取jsapiTicket
	 *
	 * @return
	 */
	private String getJsapiTicket(String appid, String secret) {
		// String cacheKey = "" + appid;
		String jsapiTicket = "";
		if (StringUtils.isEmpty(jsapiTicket)) {
			String acess_token = this.getAccessToken(appid, secret);
			String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + acess_token + "&type=jsapi";
			String backData = UtilsUrlCertificate.get(urlStr);
			logger.debug("getticket----------返回=" + backData);
			jsapiTicket = (String) net.sf.json.JSONObject.fromObject(backData).get("ticket");
		}
		return jsapiTicket;
	}

	/***
	 * 获取acess_token
	 *
	 * @return
	 */
	private String getAccessToken(String appid, String secret) {
		logger.debug("appid=" + appid + ",secret=" + secret);
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "";
		String backData = UtilsUrlCertificate.get(url);
		logger.debug("获取getAccessToken---w-------backData=" + backData);
		logger.info("获取getAccessToken---w-------backData=" + backData);
		String accessToken = (String) net.sf.json.JSONObject.fromObject(backData).get("access_token");
		return accessToken;
	}

	private String CHARS_AND_NUMBERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";

	private String getRandomString() {
		StringBuilder sb = new StringBuilder();
		int len = CHARS_AND_NUMBERS.length();
		for (int i = 0; i < 16; i++) {
			int index = (int) Math.round(Math.random() * (len - 1));
			sb.append(CHARS_AND_NUMBERS.charAt(index));
		}
		return sb.toString();
	}
}
